import React, { useState, forwardRef, useImperativeHandle } from 'react';
import _ from 'lodash';
import { nanoid } from 'nanoid';
import { Form, Button, Input, message } from 'antd';
import { DotLoading } from 'antd-mobile';
import OnlineCode from './onlineCode';
import DebounceWrapper from '@/components/DebounceWrapper';
import { LockOutlined, SafetyOutlined, UserOutlined, BorderOutlined } from '@ant-design/icons';
import styles from './loginForm.less';

const DebounceButton = DebounceWrapper(Button);

export default forwardRef(
  (
    { loginDisabled, loginLoading, initialLoading, loginTypeList, handleLogin, setLoginType },
    ref,
  ) => {
    const [form] = Form.useForm();
    const [randomNumber, setRandomNumber] = useState(nanoid(12));

    // 切换验证码
    const handleChangeCodeImage = () => {
      setRandomNumber(nanoid(12));
      form.setFields([{ name: 'code', value: '', errors: [] }]);
    };

    // 方法挂载
    useImperativeHandle(ref, () => ({
      errorHandle: ({ code, description }) => {
        console.log(code);
        const currentCode = form.getFieldValue('code');
        switch (code) {
          case 100008:
            form.setFields([
              { name: 'code', value: currentCode, errors: [description || '验证码无效'] },
            ]);
            break;
          case 100009:
            form.setFields([
              { name: 'code', value: currentCode, errors: [description || '验证码有误'] },
            ]);
            break;
          case 100001:
            setRandomNumber(nanoid(12));
            const username = form.getFieldValue('username');
            const password = form.getFieldValue('password');
            form.setFields([
              { name: 'code', value: '', errors: [] },
              { name: 'username', value: username, errors: ['账号或密码有误'] },
              { name: 'password', value: password, errors: ['账号或密码有误'] },
            ]);
            break;
          default:
            handleChangeCodeImage();
            break;
        }
      },
      updateValidCode: handleChangeCodeImage,
    }));

    // 登录
    const handleLoginClick = () => {
      form.validateFields().then((values) => {
        handleLogin(_.assign({ randomNumber }, values, { username: values.username.trim() }));
      });
    };

    // 其他登录方式按钮
    const ExtraLoginIcon = DebounceWrapper(({ type, icon, tip, disabled }) => (
      <div
        title={tip || '点我切换登录方式'}
        className={`${styles.loginExtraTypesListItem} ${disabled ? styles.disabled : null}`}
        onClick={() => {
          if (!loginLoading) {
            if (disabled) {
              message.warning(`系统未开放${tip || '该登录方式'}`);
            } else {
              setLoginType && setLoginType(type);
            }
          }
        }}
      >
        {React.createElement(icon || BorderOutlined)}
      </div>
    ));

    return (
      <div className={styles.formContent}>
        <div className={styles.loginFormTitle}>用户登录</div>
        <div className={styles.loginFormCube}>
          <Form name="default-login" form={form}>
            <div className={styles.loginFormItem}>
              <span className={styles.loginFormLabelIcon}>
                <UserOutlined className={styles.loginIcon} />
              </span>
              <Form.Item
                name="username"
                label={<UserOutlined className={styles.loginIcon} />}
                rules={[{ required: true, message: '请输入账号' }]}
              >
                <Input placeholder="请输入账号" autoComplete="off" />
              </Form.Item>
            </div>

            <div className={styles.loginFormItem}>
              <span className={styles.loginFormLabelIcon}>
                <LockOutlined className={styles.loginIcon} />
              </span>
              <Form.Item
                name="password"
                label={<LockOutlined className={styles.loginIcon} />}
                rules={[{ required: true, message: '请输入登录密码' }]}
              >
                <Input.Password placeholder="请输入密码" autoComplete="off" />
              </Form.Item>
            </div>

            <div className={styles.loginFormItem}>
              <span className={styles.loginFormLabelIcon}>
                <SafetyOutlined className={styles.loginIcon} />
              </span>
              <Form.Item
                name="code"
                label={<SafetyOutlined className={styles.loginIcon} />}
                className={styles.loginFormValidateControl}
                rules={[{ required: true, whitespace: true, message: '请输入验证码' }]}
              >
                <Input placeholder="验证码" maxLength={5} autoComplete="off" />
              </Form.Item>
              <div className={styles.loginFormValidateImage}>
                <OnlineCode randomNumber={randomNumber} changeCodeImage={handleChangeCodeImage} />
              </div>
            </div>

            <DebounceButton
              block
              htmlType="submit"
              type="primary"
              loading={loginLoading}
              onClick={() => {
                if (!loginDisabled) {
                  handleLoginClick();
                }
              }}
            >
              登录
            </DebounceButton>
          </Form>
          {!!REACT_APP_EXTRA_LOGIN && (
            <div className={styles.loginExtraTypes}>
              <span className={styles.loginExtraTypesLabel}>其他登录方式：</span>
              <div
                className={styles.loginExtraTypesList}
                style={{ pointerEvents: initialLoading ? 'none' : 'auto' }}
              >
                {loginTypeList.map(({ key, ...opts }) => (
                  <ExtraLoginIcon key={key} type={key} {...opts} />
                ))}
                <div
                  className={styles.loginTypeLoading}
                  style={{ opacity: initialLoading ? 1 : 0 }}
                >
                  <DotLoading />
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    );
  },
);
